package com.example.myapplication;

import android.Manifest;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private static final String TAG = "MainActivity";
    private Button palyButton;
    private Button pauseButton;
    private Button conButton;
    private Button upButton;
    private Button nextButton;
    private SeekBar mSeekBar;
    private TextView TextView1;
    private TextView TextView2;
    private TextView TextView3;
    private ListView listview;
    private long[] idBag;
    private String[] nameBag={"","","","",""};
    private int i = 0;
    private int x = 0;
    private int y = 0;
    private int a = 0;
    private int b = 0;
    private int c = 0;

    private MediaPlayer mediaPlayer3 = new MediaPlayer();
    private SimpleDateFormat time = new SimpleDateFormat("m:ss");

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        iniView();
        mSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                TextView2.setText(time.format(mediaPlayer3.getCurrentPosition()) + "s");
                TextView1.setText(time.format(mediaPlayer3.getDuration()) + "s");
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                int progress = seekBar.getProgress();
                //跳转到某个位置播放
                mediaPlayer3.seekTo(progress);
            }
        });
        //判断权限够不够，不够就给
        if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(MainActivity.this, new String[]{
                    Manifest.permission.WRITE_EXTERNAL_STORAGE
            }, 1);
        } else {
            iniMediaPlayercontentUri();
        }
    }

    private void iniMediaPlayercontentUri() {

        ContentResolver contentResolver = getContentResolver();
        Uri uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
        Cursor cursor = contentResolver.query(uri, null, null, null, null);

        if (cursor == null) {
            Toast.makeText(this, "query failed,这里可以处理错误", Toast.LENGTH_SHORT).show();
        } else if (!cursor.moveToFirst()) {
            Toast.makeText(this, "没有歌在设备上", Toast.LENGTH_SHORT).show();
        } else {
            Log.d(TAG, "有歌在设备");
            Toast.makeText(this, "有歌在设备", Toast.LENGTH_SHORT).show();
            int titleColumn = cursor.getColumnIndex(MediaStore.Audio.Media.TITLE);
            int idColumn = cursor.getColumnIndex(MediaStore.Audio.Media._ID);
            //歌曲数量
            int totalMusic = cursor.getCount();
            idBag = new long[totalMusic];
            listview = (ListView)findViewById(R.id.limusic);
            List<String> list = new ArrayList<String>();
            do {
                long thisId = cursor.getLong(idColumn);
                String thisTitle = cursor.getString(titleColumn);
                //这里还可以写更多过程获取更多媒体的详细数据
                idBag[i] = thisId;
                nameBag[i] = thisTitle;
                i++;
                Log.d(TAG, "当前歌曲id:" + thisId);
                Log.d(TAG, "当前歌曲title:" + thisTitle);
                list.add(thisTitle);
            } while (cursor.moveToNext());

            //使用ArrayAdapter数组适配器将界面控件和底层数据绑定在一起，这里即ListView和ArrayList绑定
            ArrayAdapter<String> adapter2 = new ArrayAdapter<String>(this,
                    android.R.layout.simple_list_item_1, list);
            listview.setAdapter(adapter2); //完成绑定


            //添加点击ListView选项的事件监听器
            listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?>parent, View view, int position, long id)
                {
                    table((int) id);
                    TextView3.setText(nameBag[(int) id]);
                    adapter2.notifyDataSetChanged();

                }
            });
        }
    }

    private void table(int h){

        if(y==0){
            b=1;
            //切换歌曲reset()很重要很重要很重要，没有会报IllegalStateException
            mediaPlayer3.reset();
            iniMediaPlayerFile(x = h);
            mediaPlayer3.start();
            new MyThre().start();
            b=0;
            y=1;
            c=h;
        }else if(y==1){
            if (c!=h){
                b=1;
                //切换歌曲reset()很重要很重要很重要，没有会报IllegalStateException
                mediaPlayer3.reset();
                iniMediaPlayerFile(x = h);
                mediaPlayer3.start();
                new MyThre().start();
                b=0;
                c=h;
            }else if(c==h){
                a=4;
                Toast(a);
            }

        }

    }

    class MyThre extends Thread {
        public void run() {
            super.run();
            do{
                int duration = mediaPlayer3.getDuration();
                //设置进度条的最大值为音乐的总时长
                mSeekBar.setMax(duration);
                //获取当前音乐播放的位置
                int currentPosition = mediaPlayer3.getCurrentPosition();
                //让进度条动起来
                mSeekBar.setProgress(currentPosition);
                if(b==1)
                    break;
            }while(mSeekBar.getProgress() <= mSeekBar.getMax());
        }
    }
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.con:
                if (y==0) {
                    a=3;
                    Toast(a);
                }else if(y==1){
                    if (!mediaPlayer3.isPlaying()) {
                        mediaPlayer3.start();
                    }else{
                        a=4;
                        Toast(a);
                    }
                }


                break;
            case R.id.pause:
                if (y==0) {
                    a=3;
                    Toast(a);
                }else if(y==1){
                    if (mediaPlayer3.isPlaying()) {
                        mediaPlayer3.pause();
                    }else{
                        a=5;
                        Toast(a);
                    }
                }

                break;
            case R.id.play:
                if (y==0) {
                    iniMediaPlayerFile(x = 0);
                    mediaPlayer3.start();
                    new MyThre().start();
                    TextView3.setText(nameBag[x]);
                    y=1;
                }else if(y==1){
                    a=2;
                    Toast(a);
                }
                break;
            case R.id.up:
                if (y==0) {
                    a=3;
                    Toast(a);
                }else if(y==1){
                    if (mediaPlayer3 != null && x <= 4 && x > 0) {
                        b=1;
                        //切换歌曲reset()很重要很重要很重要，没有会报IllegalStateException
                        mediaPlayer3.reset();
                        iniMediaPlayerFile(x - 1);
                        //这里的if只要是为了不让歌曲的序号越界，因为只有4首歌
                        if (i == 0) {
                            x = 0;
                        } else {
                            x = x - 1;
                        }
                        mediaPlayer3.start();
                        new MyThre().start();
                        TextView3.setText(nameBag[x]);
                        b=0;
                    }else if(x==0){
                        a=1;
                        Toast(a);
                    }
                }

                break;
            case R.id.next:
                if (y==0) {
                    a=3;
                    Toast(a);
                }else if(y==1){
                    if (mediaPlayer3 != null && x < 4 && x >= 0) {
                        b=1;
                        //切换歌曲reset()很重要很重要很重要，没有会报IllegalStateException
                        mediaPlayer3.reset();
                        iniMediaPlayerFile(x + 1);
                        //这里的if只要是为了不让歌曲的序号越界，因为只有4首歌
                        if (i == 4) {
                            x = 4;
                        } else {
                            x = x + 1;
                        }
                        mediaPlayer3.start();
                        new MyThre().start();
                        TextView3.setText(nameBag[x]);
                        b=0;
                    }else if(x==4){
                        a=0;
                        Toast(a);
                    }
                }
                break;
            default:
                break;
        }
    }

    protected void Toast(int z){
        if (z==0){
            Toast.makeText(this, "后面没有歌曲了", Toast.LENGTH_SHORT).show();
        }
        if (z==1){
            Toast.makeText(this, "前面没有歌曲了", Toast.LENGTH_SHORT).show();
        }
        if (z==2){
            Toast.makeText(this, "音乐已播放", Toast.LENGTH_SHORT).show();
        }
        if (z==3){
            Toast.makeText(this, "请先播放音乐", Toast.LENGTH_SHORT).show();
        }
        if (z==4){
            Toast.makeText(this, "已经播放音乐", Toast.LENGTH_SHORT).show();
        }
        if (z==5){
            Toast.makeText(this, "已经暂停播放音乐", Toast.LENGTH_SHORT).show();
        }
    }

    private void iniView() {

        palyButton = (Button) findViewById(R.id.play);
        pauseButton = (Button) findViewById(R.id.pause);
        conButton = (Button) findViewById(R.id.con);
        upButton = (Button) findViewById(R.id.up);
        nextButton = (Button) findViewById(R.id.next);
        mSeekBar = (SeekBar) findViewById(R.id.seekbar);
        TextView1 = (TextView) findViewById(R.id.text1);
        TextView2 = (TextView) findViewById(R.id.text2);
        TextView3 = (TextView) findViewById(R.id.text3);
        palyButton.setOnClickListener(this);
        pauseButton.setOnClickListener(this);
        conButton.setOnClickListener(this);
        upButton.setOnClickListener(this);
        nextButton.setOnClickListener(this);
        mSeekBar.setOnClickListener(this);
        TextView1.setOnClickListener(this);
        TextView2.setOnClickListener(this);
    }
    private void iniMediaPlayerFile(int dex) {
        long id = idBag[dex];
        Uri contentUri = ContentUris.withAppendedId(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, id);
        mediaPlayer3.setAudioStreamType(AudioManager.STREAM_MUSIC);
        try {
            mediaPlayer3.setDataSource(this, contentUri);
            mediaPlayer3.prepare();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
